package com.example.pattern.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 懒汉式 静态内部类实现
 *  通过 jvm加载静态内部类就初始化完成，只有在用的时候才初始化
 */
public class StaticInnerClassSingletonTest {

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        StaticInnerClassSingleton.getInstance();
        new Thread(() -> {
            StaticInnerClassSingleton instance = StaticInnerClassSingleton.getInstance();
            System.out.println(instance);
        }).start();
        new Thread(() -> {
            StaticInnerClassSingleton instance = StaticInnerClassSingleton.getInstance();
            System.out.println(instance);
        }).start();

        /**
         * 可以通过反射来破解
         */
        /*Constructor<StaticInnerClassSingleton> declaredConstructor = StaticInnerClassSingleton.class.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        StaticInnerClassSingleton staticInnerClassSingleton = declaredConstructor.newInstance();

        StaticInnerClassSingleton instance = StaticInnerClassSingleton.getInstance();
        System.out.println(staticInnerClassSingleton == instance);*/

    }

}

class StaticInnerClassSingleton{

    private static class InnerClassHolder{
        private static StaticInnerClassSingleton instance = new StaticInnerClassSingleton();
    }

    private StaticInnerClassSingleton(){}

    public static StaticInnerClassSingleton getInstance(){
        return InnerClassHolder.instance;
    }

}
